<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="UTF-8" />
    <title>Answer</title>
    <script
      crossorigin
      src="https://unpkg.com/react@16/umd/react.development.js"
    ></script>
    <script
      crossorigin
      src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"
    ></script>
    <script
      crossorigin
      src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"
    ></script>
    <script src="https://cdn.jsdelivr.net/npm/babel-regenerator-runtime@6.5.0/runtime.min.js"></script>
  </head>
  <body>
    <div class="main">
      <div class="section" id="app1"></div>
    </div>
    <script type="text/babel">
      function createTestTrack(width, height) {
        const canvas = document.createElement("canvas");
        canvas.width = width;
        canvas.height = height;
        const ctx = canvas.getContext("2d");

        const drawAnimation = () => {
          ctx.clearRect(0, 0, canvas.width, canvas.height);
          ctx.fillStyle = "rgb(200, 200, 200)";
          ctx.fillRect(0, 0, canvas.width, canvas.height);

          const date = new Date();
          ctx.font = "38px Monaco,Consolas";
          ctx.textAlign = "center";
          ctx.fillStyle = "red";
          const hours = ("0" + date.getHours()).slice(-2);
          const minutes = ("0" + date.getMinutes()).slice(-2);
          const seconds = ("0" + date.getSeconds()).slice(-2);
          const milliseconds = ("00" + date.getMilliseconds()).slice(-3);
          ctx.fillText(
            `${hours}:${minutes}:${seconds}.${milliseconds}`,
            canvas.width / 2,
            85
          );

          requestAnimationFrame(drawAnimation);
        };
        setTimeout(() => drawAnimation(), 0);

        const [track] = canvas.captureStream().getVideoTracks();
        return track;
      }

      const App = () => {
        const videoRef = React.useRef();

        React.useEffect(() => {
          (async () => {
            const socket = new WebSocket("ws://localhost:8878");
            await new Promise((r) => (socket.onopen = r));
            console.log("open websocket");

            const offer = await new Promise(
              (r) => (socket.onmessage = (ev) => r(JSON.parse(ev.data)))
            );
            console.log("offer", offer.sdp);

            const peer = new RTCPeerConnection({
              iceServers: [],
            });
            peer.onicecandidate = ({ candidate }) => {
              if (!candidate) {
                const sdp = JSON.stringify(peer.localDescription);
                console.log(peer.localDescription.sdp);
                socket.send(sdp);
              }
            };
            peer.oniceconnectionstatechange = () => {
              console.log(
                "oniceconnectionstatechange",
                peer.iceConnectionState
              );
            };
            const stream = new MediaStream();
            peer.ontrack = (e) => {
              console.log("ontrack", e);
              stream.addTrack(e.track);
              videoRef.current.srcObject = stream;
            };
            // const video = createTestTrack(640, 360);
            const [video] = (
              await navigator.mediaDevices.getUserMedia({
                video: true,
              })
            ).getTracks();
            const [audio] = (
              await navigator.mediaDevices.getUserMedia({
                audio: true,
              })
            ).getTracks();
            peer.addTrack(video);
            peer.addTrack(audio);

            await peer.setRemoteDescription(offer);
            const answer = await peer.createAnswer();
            await peer.setLocalDescription(answer);
          })();
        }, []);

        return (
          <div>
            answer
            <video ref={videoRef} autoPlay />
          </div>
        );
      };

      ReactDOM.render(<App />, document.getElementById("app1"));
    </script>
  </body>
</html>
